package com.rose.datax.dataxadmin.manager.impl;

import com.rose.datax.dataxadmin.entity.DataTable;
import com.rose.datax.dataxadmin.entity.DbConnection;
import com.rose.datax.dataxadmin.manager.DatabaseViewerMng;
import com.rose.datax.dataxadmin.mapper.DbConnectionMapper;
import com.rose.datax.dataxadmin.utils.DbUtils;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DatabaseViewerMngImpl implements DatabaseViewerMng {

    @Resource
    private DbConnectionMapper mapper;

    @Override
    public List<DataTable> getSourceTables(long sourceId, String database) {
        List<DataTable> results = new ArrayList<>();
        DbConnection dbConnection = mapper.selectById(sourceId);
        try {
            String sql = "select ut.table_name,(ut.data_length+ut.index_length)/1024/1024 as size_MB, ut.table_rows  from information_schema.tables ut where ut.table_schema=? and ut.table_type='base table' order by size_MB desc";
            @Cleanup
            Connection connection = DbUtils.getConnection(dbConnection.getJdbcURL(), dbConnection.getUsername(), dbConnection.getPassword());
            @Cleanup
            PreparedStatement pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, database);
            @Cleanup
            ResultSet rs = pstmt.executeQuery();
            DataTable table = null;
            if(null != rs){
                while (rs.next()){
                    table = new DataTable();
                    table.setTableName(rs.getString(1));
                    table.setTableSize(rs.getFloat(2));
                    table.setRows(rs.getLong(3));
                    results.add(table);
                }
            }
        }catch (SQLException e){
            log.error(e.getMessage());
        }
        return results;
    }

}
